<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <span>用户登录</span>
        </div>
      </template>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="80px"
        @submit.prevent="handleLogin"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleLogin"
            :loading="loading"
            style="width: 100%"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="tips">
        <p>测试账号：</p>
        <p>用户名: admin 密码: 123456</p>
        <p>用户名: user  密码: 123456</p>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { loginApi } from '@/api/request'
import { ElMessage } from 'element-plus'

// 表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 表单验证规则
const loginRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur' }
  ]
})

// 表单引用
const loginFormRef = ref<FormInstance>()

// 状态
const loading = ref(false)
const router = useRouter()

// 登录处理函数
const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true

      try {
        // 调用真实登录接口
        const response = await loginApi({
          username: loginForm.username,
          password: loginForm.password
        })

        if (response.code === 200) {
          // 保存用户信息和token到 localStorage
          localStorage.setItem('accessToken', response.data.accessToken)
          localStorage.setItem('refreshToken', response.data.refreshToken)
          localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo))

          // 跳转到首页
          router.push('/')

          ElMessage.success('登录成功')
        } else {
          ElMessage.error(response.message || '登录失败')
        }
      } catch (error: any) {
        console.error('登录失败:', error)
        if (error.response && error.response.data) {
          ElMessage.error(error.response.data.message || '登录失败，请检查用户名和密码')
        } else {
          ElMessage.error('登录失败，请检查网络或稍后重试')
        }
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
  margin: 0;
  padding: 20px;
  box-sizing: border-box;
}

.login-card {
  width: 100%;
  max-width: 400px;
  max-height: calc(100vh - 40px);
  overflow: hidden;
}

.tips {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
  max-height: 100px;
  overflow: hidden;
}

.tips p {
  margin: 5px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    padding: 10px;
  }

  .login-card {
    max-height: calc(100vh - 20px);
  }
}

@media (max-height: 600px) {
  .login-container {
    align-items: flex-start;
    padding-top: 10px;
  }

  .login-card {
    max-height: calc(100vh - 20px);
  }
}
</style>
